package org.csu.lestore.api.controller;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.csu.lestore.api.bean.AliPayBean;
import org.csu.lestore.api.common.CommonResponse;
import org.csu.lestore.api.entity.Item;
import org.csu.lestore.api.entity.OrderItem;
import org.csu.lestore.api.entity.Orders;
import org.csu.lestore.api.service.OrderService;
import org.csu.lestore.api.service.PayService;
import org.csu.lestore.api.util.RandomUtils;
import org.csu.lestore.api.vo.AccountVO;
import org.csu.lestore.api.vo.OrderVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/order/")
public class OrderController {

    //创建Logger对象
    private static Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private PayService payService;
    @Autowired
    private OrderService orderService;

    @GetMapping("{orderId}")//根据orderId获取订单
    @ResponseBody
    public CommonResponse<OrderVO> getOrder(@PathVariable("orderId") int orderId,HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            return orderService.getOrder(orderId);
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @GetMapping("{orderId}/orderItem")//根据orderId获取订单下商品
    @ResponseBody
    public CommonResponse<IPage<OrderItem>> getOrderItemList(@PathVariable("orderId") int orderId,HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            return orderService.getOrderItemListInPage(1,2147483647,orderId);
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @GetMapping("orderListByUserId")//根据userId获取某账号的所有订单
    @ResponseBody
    public CommonResponse<IPage<OrderVO>> getOrderList(@RequestParam("size") int size,
                                                       @RequestParam("curPage") int curPage,
                                                       @RequestParam("userId") int userId,
                                                       HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            if(login_accountVO.getStatus()=='M'){//要求管理员权限
                return orderService.getOrderListInPage(curPage,size,userId);
            }else {
                return CommonResponse.createForError("权限不足");
            }
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @GetMapping("orderList")//获取登录账号的所有订单
    @ResponseBody
    public CommonResponse<IPage<OrderVO>> getOrderList(HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            return orderService.getOrderListInPage(1,2147483647,login_accountVO.getUserId());
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @GetMapping("allOrderList")//获取所有订单
    @ResponseBody
    public CommonResponse<IPage<OrderVO>> getAllOrderList(@RequestParam("size") int size,
                                                          @RequestParam("curPage") int curPage,
                                                          HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            if(login_accountVO.getStatus()=='M'){//要求管理员权限
                return orderService.getOrderListInPage(curPage,size);
            }else {
                return CommonResponse.createForError("权限不足");
            }
        }
        else{
            return CommonResponse.createForError("未登录");
        }

    }

    @PostMapping("insertOrder")//添加订单
    @ResponseBody
    public CommonResponse<Orders> insertOrder(@RequestBody Orders orders,
                                                      HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            orders.setUserId(login_accountVO.getUserId());
            return orderService.insertOrder(orders);
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @PostMapping("insertOrderItem")//添加订单商品
    @ResponseBody
    public CommonResponse<Orders> insertOrderItem(@RequestBody OrderItem orderItem,
                                                  HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            orderService.insertOrderItem(orderItem);
            return CommonResponse.createForSuccessMessage("插入订单条目成功");
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @PostMapping("deleteOrder")//删除订单
    @ResponseBody
    public CommonResponse<Orders> deleteOrder(@RequestParam("orderId") int orderId,
                                              HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            return orderService.deleteOrder(orderId);
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @PostMapping("setOrderState")//设置订单状态
    @ResponseBody
    public CommonResponse<Orders> setOrderState(@RequestParam("orderId") int orderId,
                                                @RequestParam("orderState") char orderState,
                                                HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            return orderService.setOrderState(orderId,orderState);
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @PostMapping("updateOrder")//修改订单
    @ResponseBody
    public CommonResponse<Orders> updateOrder(@RequestBody Orders orders, HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            return orderService.updateOrder(orders);
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    //订单号,订单名称,付款金额,上品描述 //需要传入一个pram 金额totalAmount 返回response 里面 data为支付网页 前端document.write(resp)
    @RequestMapping("pay")
    @ResponseBody
    public CommonResponse<String> alipay(String totalAmount) throws AlipayApiException {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = formatter.format(date);

        String outTradeNo = dateStr + RandomUtils.randomString(4);
        String subject = "letstore";
        String body = "一刀99999";

        System.out.println(outTradeNo);
//        logger.info("商户订单号为{},订单名称为{},付款金额为{},商品描述{}", outTradeNo, subject, totalAmount, body);
        AliPayBean alipayBean = new AliPayBean();
        alipayBean.setOut_trade_no(outTradeNo);
        alipayBean.setSubject(subject);
        alipayBean.setTotal_amount(totalAmount);
        alipayBean.setBody(body);

        return CommonResponse.createForSuccess(payService.aliPay(alipayBean));
    }
}
